<template>
  <div class="category-management">
    <el-row class="toolbar" type="flex" justify="space-between">
      <el-col :span="12">
        <el-input
            v-model="searchName"
            placeholder="输入分类名称进行搜索"
            clearable
            @input="searchCategory"
        />
      </el-col>
      <el-col :span="6" style="text-align: right;">
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">添加分类</el-button>
      </el-col>
    </el-row>

    <el-table
        :data="categories"
        style="width: 100%"
        @row-click="handleRowClick"
        :row-class-name="(row) => row.id === selectedRowId ? 'selected-row' : ''"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteCategory(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogTitle"
        @close="resetForm"
        width="400px"
    >
      <el-form :model="categoryForm" ref="categoryForm" label-width="80px">
        <el-form-item label="分类名称" :rules="[ { required: true, message: '请输入分类名称', trigger: 'blur' } ]">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      categories: [],         // 岗位分类列表
      searchName: "",         // 搜索框绑定
      dialogVisible: false,   // 对话框显示状态
      dialogTitle: "",        // 对话框标题
      categoryForm: {         // 表单数据
        id: null,
        name: "",
      },
      selectedRowId: null,    // 当前选中的行ID
    };
  },
  methods: {
    // 获取所有岗位分类
    fetchCategories() {
      axios.get("/api/category")
          .then(response => {
            this.categories = response.data.data;
          })
          .catch(error => {
            console.error("获取岗位分类失败:", error);
          });
    },

    // 模糊搜索岗位分类
    searchCategory() {
      axios.get("/api/category/name", { params: { name: this.searchName } })
          .then(response => {
            this.categories = response.data.data;
          })
          .catch(error => {
            console.error("搜索岗位分类失败:", error);
          });
    },

    // 打开添加对话框
    openAddDialog() {
      this.dialogTitle = "添加岗位分类";
      this.categoryForm = { id: null, name: "" };
      this.dialogVisible = true;
    },

    // 打开编辑对话框
    openEditDialog(row) {
      this.dialogTitle = "编辑岗位分类";
      this.categoryForm = { ...row };
      this.dialogVisible = true;
    },

    // 保存分类（添加/编辑）
    saveCategory() {
      const isAdd = !this.categoryForm.id;  // 判断是添加还是编辑
      const apiUrl = isAdd ? "/api/category" : `/api/category/${this.categoryForm.id}`;
      const method = isAdd ? "post" : "put";

      axios[method](apiUrl, this.categoryForm)
          .then(() => {
            this.fetchCategories();  // 刷新分类列表
            this.dialogVisible = false;

            // 成功弹窗
            this.$message.success(isAdd ? "添加分类成功" : "更新分类成功");
          })
          .catch(error => {
            console.error(isAdd ? "添加分类失败" : "更新分类失败", error);

            // 失败弹窗
            this.$message.error(isAdd ? "添加分类失败" : "更新分类失败");
          });
    },

    // 删除分类
    deleteCategory(id) {
      this.$confirm("确定删除该分类吗?", "提示", {
        type: "warning",
      })
          .then(() => {
            axios.delete(`/api/category/${id}`)
                .then(() => {
                  this.fetchCategories();  // 刷新分类列表
                  // 成功弹窗
                  this.$message.success("删除分类成功");
                })
                .catch(error => {
                  console.error("删除分类失败:", error);
                  // 失败弹窗
                  this.$message.error("删除分类失败");
                });
          })
          .catch(() => {});
    },

    // 选中行时的处理
    handleRowClick(row) {
      this.selectedRowId = row.id;
    },

    // 重置表单
    resetForm() {
      this.$refs.categoryForm.resetFields();
    }
  },

  created() {
    this.fetchCategories();  // 组件创建时获取所有分类
  },
};

</script>

<style scoped>
.category-management {
  padding: 20px;
}

.selected-row {
  background-color: #f2f2f2;
}

.toolbar {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
